using System;
using IDeal.Models;

namespace IDeal.Services
{
    public class IssuersCache : IIssuersCache
    {
        private readonly IIssuersStorage _storage;
        private readonly IIDealServices _iDealServices;
        private readonly IClock _clock;
        private Lazy<IssuersDirectory> _issuers;
        public TimeSpan RefreshAtAgeThreshold { get; set; }
        public IssuersDirectory Issuers
        {
            get
            {
                if(_clock.UtcNow - _issuers.Value.TimeStamp >= RefreshAtAgeThreshold)
                    Refresh();

                return _issuers.Value;
            }
        }

        public IssuersCache(IIssuersStorage storage, IIDealServices iDealServices, IClock clock)
        {
            _storage              = storage;
            _iDealServices        = iDealServices;
            _clock                = clock;
            _issuers              = new Lazy<IssuersDirectory>(LoadCachedIssuers, true);
            RefreshAtAgeThreshold = TimeSpan.FromDays(1);
        }

        public void Refresh()
        {
            var response = _iDealServices.GetIssuers();

            response.Directory.TimeStamp = _clock.UtcNow;
            _storage.Save(response.Directory);
            _issuers = new Lazy<IssuersDirectory>(LoadCachedIssuers, true);
        }

        private IssuersDirectory LoadCachedIssuers()
        {
            return _storage.Load();
        }
    }
}